import { Component, forwardRef, Injector, Input } from '@angular/core'
import { NG_VALUE_ACCESSOR } from '@angular/forms'
import { Observable } from 'rxjs'

import { AbstractCustomSelectComponent } from '../custom-select/custom-select.component'
import { IGenericPagination } from '@shared/interfaces/pagination'
import { Channel, IChannelQueryParams } from '@shared/interfaces/channel'
import { ChannelService } from '@shared/services/channel.service'
import { EPaymentBrand } from '@shared/enums'

@Component({
  selector: 'app-channel-merchant-select',
  templateUrl: './channel-merchant-select.component.html',
  styles: [],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => ChannelMerchantSelectComponent),
      multi: true,
    },
  ],
})
export class ChannelMerchantSelectComponent extends AbstractCustomSelectComponent<Channel, IChannelQueryParams> {
  constructor(private channelService: ChannelService, public injector: Injector) {
    super(injector)
  }

  @Input()
  set chanCode(val: EPaymentBrand) {
    this._chanCode = val
    this._params.chanCode = val
  }

  _chanCode: EPaymentBrand

  _params: IChannelQueryParams = {
    size: 10,
    page: 1,
  }
  deduplicate(list: Channel[]): Channel[] {
    return list
  }

  compareFn = (o1: Channel, o2: Channel) => {
    if (o1 instanceof Channel && o2 instanceof Channel) {
      return o1.chanCode === o2.chanCode && o1.chanMerID === o2.chanMerID
    }

    return o1 === o2
  }

  query(params: IChannelQueryParams): Observable<IGenericPagination<Channel>> {
    return this.channelService.paging(params)
  }

  getParams(): IChannelQueryParams {
    return this._params
  }

  loadMore(): void {
    if (this.isLoading) {
      return
    }
    this.isLoading = true
    this._params.page++
    this.searchChange$.next(this.getParams())
  }

  onSearch(value: string): void {
    this.isLoading = true
    this._options = []
    this._params.page = 1
    this._params.keyword = value
    this.searchChange$.next(this.getParams())
  }
}
